"""
animeRSS.py
by Jimbo1023
Trawls through anime fansubber RSS feeds for new releases to followed series
"""
__version__ = "(24 Oct 2010)"

import urllib, time
from datetime import datetime

def readConfig(cFile):
   # read in the config file based on a '||' delimiter
   theC = open(cFile, 'r')
   configuration = {}
   for theLine in theC:
      if theLine.strip() == '' or theLine.split('#')[0].strip() == '':
         continue
      theLine = theLine.split('#')[0].strip()
      key, value = theLine.split('||')
      key = key.strip()
      value = value.strip()
      if key in configuration:
         configuration[key].append(value)
      else:
         configuration[key] = [value]
   return configuration

def writeAlert(aFile, alert):
   theA = open(aFile, 'a')
   theA.write(alert + "\n")
   theA.close()

def writeConfig(cFile, configuration):
   cFile = open(cFile, 'w')
   for theAnime in configuration['anime']:
      cFile.write("anime||%s\n" % theAnime)
      cFile.write("%sTitle||%s\n" % (theAnime, configuration[theAnime+"Title"][0]))
      for fansubber in configuration[theAnime+"Fansubber"]: 
         cFile.write("%sFansubber||%s\n" % (theAnime, fansubber))
      cFile.write("%sRecent||%s\n" % (theAnime, configuration[theAnime+"Recent"][0]))
      cFile.write("\n")
   cFile.close()

configFile = "animeRSS.cfg"      # TODO - change this to a command line argument
alertFile = "animeAlerts.txt"    # TODO - ditto with above
firstRun = True   # goes through all the entries in an RSS the first time you run the script
                  # just in case you missed on while not running it

while True:
   theConfig = readConfig(configFile)
   for theAnime in theConfig['anime']:
      for fansubberRSS in theConfig[theAnime+"Fansubber"]:
         updated = False # used in the startup run just in case there's more than one entry for a series
         print "Checking %s for %s" % (fansubberRSS, theAnime)
         try: f = urllib.urlopen(fansubberRSS)
         except(IOError): continue
         rssBody = f.read()
         f.close()
         if firstRun:
            theItems = rssBody.split("<item>")
            for item in theItems:
               updated = False
               if "<pubDate>" in item:
		  pubDate = item[item.find("<pubDate>")+9 : item.find("</pubDate>")]
               if theConfig[theAnime+"Title"][0] in item:
                  if pubDate.startswith(theConfig[theAnime+"Recent"][0]):
                     # we saw this one already
                     updated = True
                     break
                  if not pubDate.startswith(theConfig[theAnime+"Recent"][0]):
                      print "Found something! Check alert file"
                      try:
                         # this script can use the PyAudiere package, but it isn't strictly necessary
                         # http://pyaudiere.org/
                         # still in testing
                         import audiere
                         device = audiere.open_device()
                         boink = device.open_file("beep.wav")
                         boink.play()
                      except(NameError): pass
                      writeAlert(alertFile, "%s found!\n%s\n%s\n" % (theConfig[theAnime+"Title"][0], fansubberRSS, pubDate))
                      theConfig[theAnime+"Recent"] = [pubDate]
                      writeConfig(configFile, theConfig)
                      updated = True
                      break
            if updated: break
         else:
            newestDate = rssBody[rssBody.find("<pubDate>")+9 : rssBody.find("</pubDate>")]
            newestItem = rssBody[rssBody.find("<item>") : rssBody.find("</item>")]
            if theConfig[theAnime+"Title"][0] in newestItem:
               if not newestDate.startswith(theConfig[theAnime+"Recent"][0]):
                  print "Found something! Check alert file"
                  writeAlert(alertFile, "%s found!\n%s\n%s\n" % (theConfig[theAnime+"Title"][0], fansubberRSS, newestDate))
                  theConfig[theAnime+"Recent"] = [newestDate]
                  writeConfig(configFile, theConfig)
   firstRun = False
   print "Taking a little nap..."
   time.sleep(900) # wait 15 minutes before going again
